<template>
  <el-dialog v-model="open" title="退订" width="600px" append-to-body :close-on-click-modal="false">
    <el-form ref="unsubRef" :model="form" :rules="rules" label-width="150px">
      <el-form-item label="实付金额">
        <span v-if="form.payStatus=='0'">0</span>
        <span v-else>
          {{ form.finalOrderAmount }}
        </span>
      </el-form-item>
      <el-form-item label="应退订金额">
        <span v-if="form.payStatus=='0'">0</span>
        <span v-else>
          {{ subAmount }}
        </span>
      </el-form-item>
      <el-form-item label="实际退订金额" prop="amount">
        <el-input v-model="form.amount" type="number" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :disabled="btnDisabled" @click="submitForm">提 交</el-button>
        <el-button :disabled="btnDisabled" @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrentInstance, reactive } from '@vue/runtime-core'
import { watch } from 'vue'
import { toRefs } from '@vueuse/shared'
import { getCancelOrderPrice, unSubscribeOrder } from '../../../../../api/ven/reserve'

const { proxy } = getCurrentInstance()

const props = defineProps({
  props: {
    type: Object,
    default: () => ({
      open: false,
      data: {}
    })
  }
})
const emit = defineEmits(['submitForm'])

const data = reactive({
  form: {},
  rules: {
    amount: [{
      validator: (rule, value, callback) => {
        // if (!value) {
        //   callback('必填')
        //   return
        // }

        const canAmount = form.value.payStatus == '0' ? 0 : parseFloat(form.value.finalOrderAmount)
        if (value < 0 || value > canAmount) {
          callback('金额有误')
          return
        }
        callback()
      }, required: true, trigger: 'blur' }]
  },
  btnDisabled: false,
  subAmount: 0
})
const { open } = toRefs(props.props)
const { form, rules, btnDisabled, subAmount } = toRefs(data)

watch(open, (val) => {
  if (val) {
    btnDisabled.value = false
    form.value = props.props.data
    if (form.value.payStatus == '0') {
      subAmount.value = 0
      form.value.amount = subAmount.value
    } else {
      getCancelOrderPrice(form.value.id)
        .then((res) => {
          subAmount.value = res.data
          form.value.amount = res.data
        })
    }
  } else {
    proxy.resetForm('unsubRef')
  }
})

function submitForm() {
  proxy.$refs['unsubRef'].validate((valid) => {
    if (valid) {
      proxy.$modal.confirm('确定退订')
        .then(() => {
          unSubscribeOrder(form.value.id, {
            data: form.value.amount
          }).then(() => {
            btnDisabled.value = true
            proxy.$modal.msgSuccess('操作成功', () => {})
            open.value = false
            emit('submitForm')
          })
        })
    }
  })
}

function cancel() {
  open.value = false
}

</script>

<style scoped lang="scss">
</style>
